import React, { useMemo, useState } from "react";
// import XlCheckBox from "@/components/Form/XlCheckBox";
import { adPositionTypes } from "@/constants/types";
import { PlusOutlined } from "@ant-design/icons";
import { Button, Form, Image, Input, Modal, Select, Space, Table, TableColumnType, message } from "antd";
import { fetchAdList, adAdd, adUpdate, fetchAdPageOptions, adOffSale, adOnSale, fetchAdTabNum, adBindAdSlot, adRefreshAdData } from "../services";
import { useModel } from "@umijs/max";
import { useComponentDidMount } from "@/hooks";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { useRequest } from "ahooks";
import AddAd from "../modals/AddAd";
import UpdateAd from "../modals/UpdateAd";
import XlRadio from "@/components/Form/XlRadio";
import AdBindPosition from "../modals/AdBindPosition";

const {Item} = Form;

const AdManage = () => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0
  });
  const [form] = Form.useForm();
  const {getDict} = useModel('dictModel');
  const [status, setStatus] = useState<string>('all');
  const [tabNumObj, setTabNumObj] = useState<any>({});
  const [adPages, setAdPages] = useState([]);

  // const targetType = getDict('targetType');
  const adStatus = getDict('adStatus');

  // modal
  const [currentRow, setCurrentRow] = useState(null);
  const [addVisible, setAddVisible] = useState(false);
  const [updateVisible, setUpdateVisible] = useState(false);
  const {loading: addLoading, runAsync: addApi} = useRequest(adAdd, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(adUpdate, {manual: true});
  // bind position
  const [bindVisible, setBindVisible] = useState(false);
  const {loading: bindLoading, runAsync: bindApi} = useRequest(adBindAdSlot, {manual: true});


  const fetchTabNumApi = async (params: any) => {
    const res = await fetchAdTabNum(params);
    setTabNumObj(res || {});
  }

  const fetchPages = () => {
    fetchAdPageOptions().then(
      res => {
        setAdPages((res || []).map((v: any) => ({value: v.id, label: v.name})));
      }
    )
  }
  const search = async (params: any) => {
    const res = await fetchAdList({
      ...params,
      status: !params?.status || params?.status === 'all' ? undefined : params?.status
    });
    setDataSource(res?.data || []);
    setPagination({
      ...params,
      total: res?.total
    });
  }
  
  const refreshData = () => {
    const params = form.getFieldsValue();
    search({
      ...params,
      pageNum: 1,
      pageSize: 20,
      status
    });
    fetchTabNumApi(params);
  }

  const addProps = {
    visible: addVisible,
    title: '新增广告',
    loading: addLoading,
    onCancel: () => {
      setAddVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await addApi(params);
      if (res?.code === '0') {
        addProps.onCancel();
        refreshData();
      }
    }
  }
  const updateProps = {
    visible: updateVisible,
    title: '编辑广告',
    loading: updateLoading,
    currentRow,
    onCancel: () => {
      setUpdateVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const res = await updateApi(params);
      if (res?.code === '0') {
        updateProps.onCancel();
        refreshData();
      }
    }
  }
  const bindAdSlotProps = {
    visible: bindVisible,
    title: '绑定广告位',
    loading: bindLoading,
    currentRow,
    onCancel: () => {
      setBindVisible(false);
      setCurrentRow(null);
    },
    onSubmit:async (params:any) => {
      const res = await bindApi(params);
      if (res.code === '0') {
        bindAdSlotProps.onCancel();
        refreshData();
      }
    }
  }


  const handleEdit = (record: any) => {
    setCurrentRow(record);
    setUpdateVisible(true);
  }
  const handleAdd = () => {
    setAddVisible(true);
  }
  const handleOnSale = (record: any) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定上架？',
      onOk: () => {
        adOnSale({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              message.success("操作成功!");
              refreshData();
            }
          }
        )
      }
    });
  }
  const handleOffSale = (record: any) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定下架？',
      onOk: () => {
        adOffSale({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              message.success("操作成功!");
              refreshData();
            }
          }
        )
      }
    });
  }
  const handleRefreshAdSlot = (record: any) => {
    Modal.confirm({
      title: "温馨提示",
      content: "是否要刷新广告位",
      onOk: () => {
        adRefreshAdData({adId: record?.id}).then(
          res => {
            if (res?.code === '0') {
              message.success("刷新成功!");
              refreshData();
            }
          }
        )
      }
    });
  }
  const handleBindAdSlot = (record: any) => {
    setCurrentRow(record);
    setBindVisible(true);
  }

  const handleSearch = () => {
    const params = form.getFieldsValue();
    search({
      ...params,
      pageNum: 1,
      pageSize: 20,
      status
    });
  }
  const handleReset = () => {
    form.resetFields();
    search({
      pageNum: 1,
      pageSize: 20,
      status
    });
  }
  // status change
  const handleStatusChange = (val: string) => {
    const params = form.getFieldsValue();
    setStatus(val);
    search({
      ...params,
      pageNum: 1,
      pageSize: 20,
      status: val
    });
    fetchTabNumApi(params);
  }

  const composeOrderStatusMaps = useMemo(() => {
    const numObj = {
      all: 'totalNum',
      0: 'waitOnSaleNum',
      1: 'onSaleNum',
      2: 'offSaleNum'
    };
    return [{label: '全部', value: 'all'}, ...adStatus].map((v: {label: string, value: string}) => ({
      ...v,
      label: tabNumObj?.[numObj?.[v?.value]] > 0 ? `${v?.label} (${tabNumObj?.[numObj?.[v?.value]]})` : v.label
    }))
  }, [JSON.stringify(tabNumObj), JSON.stringify(adStatus)]);

  const columns: TableColumnType<adPositionTypes> [] = [
    {
      title: '广告名称',
      dataIndex: 'name',
      fixed:'left',
      ellipsis: true,
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => <XlTableDictColumn value={record?.status} type="adStatus" />
    },
    {
      title: '广告标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 150
    },
    {
      title: '广告位',
      dataIndex: 'slotName',
      ellipsis: true,
      width: 150
    },
    {
      title: '广告图片',
      dataIndex: 'imagePath',
      width: 150,
      render: (_, record) => <Image src={record?.imageUrl} alt={record?.imageName} />
    },
    {
      title: '关联标签',
      dataIndex: 'linkTagName',
      width: 120
    },
    {
      title: '跳转',
      dataIndex: 'targetType',
      width: 120,
      render: (_, record) => <XlTableDictColumn value={record?.targetType} type="targetType" />
    },
    {
      title: '关联活动名称',
      dataIndex: 'linkActivityName',
      width: 150
    },
    {
      title: '链接地址',
      dataIndex: 'targetPath',
      ellipsis: true,
      width: 150
    },
    {
      title: '投放时间',
      dataIndex: 'startTime',
      width: 300,
      render: (_, record) => <>{record?.startTime} - {record?.endTime}</>
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      width: 120
    },
    {
      title: '操作',
      fixed:'right',
      width: 300,
      dataIndex: 'options',
      render: (_, record: adPositionTypes) => {
        return (
          <Space>
            {record?.status !== '1' && <Button type="link" onClick={() => handleOnSale(record)}>上架</Button>}
            {record?.status === '1' && <Button type="link" onClick={() => handleOffSale(record)}>下架</Button>}
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleBindAdSlot(record)}>绑定</Button>
            <Button type="link" onClick={() => handleRefreshAdSlot(record)}>刷新</Button>
          </Space>
        );
      }
    },
  ]


  useComponentDidMount(() => {
    fetchPages();
    search({
      pageNum: 1,
      pageSize: 20,
      status
    });
    fetchTabNumApi({});
  })

  return (
   <>
    <Form form={form} layout="inline">
        <Item label="广告名称" name="name" style={{marginBottom: 15}}>
          <Input onPressEnter={handleSearch} />
        </Item>
        <Item label="广告页" name="pageId" style={{marginBottom: 15}}>
          <Select options={adPages} style={{width: 183}} />
        </Item>
        <Space style={{marginBottom: 20}}>
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button type="default" onClick={handleReset}>重置</Button>
        </Space>
    </Form>
    <div style={{display: 'flex', justifyContent:'space-between', flexWrap: 'wrap'}}>
        <div >
          <XlRadio.ButtonRadioGroup value={status} onChange={(val: any) => handleStatusChange(val.value)} options={composeOrderStatusMaps} />
        </div>
        <Space style={{display: 'flex', justifyContent: 'flex-end', }}>
          <Button type="primary" onClick={handleAdd}><PlusOutlined />新建广告</Button>
        </Space>
      </div>
      <Table
        className="mt10"
        bordered
        rowKey="id"
        dataSource={dataSource}
        columns={columns}
        scroll={{x: calculateTableWidth(columns), y: 620}}
        pagination= {{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            const params = form.getFieldsValue();
            search({...params, pageNum, pageSize});
          }
        }}
      />
      {addVisible && <AddAd {...addProps} />}
      {updateVisible && <UpdateAd {...updateProps} />}
      {bindVisible && <AdBindPosition {...bindAdSlotProps} />}
    </>
  );
}
export default AdManage;